package com.bobgao.my_first_demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
public class MailController {

    @Autowired
    private JavaMailSender javaMailSender;

    // 获取yml配置的发送者邮箱
    @Value("${spring.mail.username}")
    private String mainUserName;

    @RequestMapping(value = "/sendMail", method = RequestMethod.POST)
    public String sendSimpleMail(String mailAccount) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(mainUserName);
        // 设置邮件接收者
        message.setTo(mailAccount);
        // 设置邮件的主题
        message.setSubject("验证码");
        // 设置邮件的正文
        String text = "您的验证码为：" + randomCode() + "请勿泄露给他人。";
        message.setText(text);
        // 发送邮件
        javaMailSender.send(message);
        return randomCode();
    }

    public static String randomCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(r);
        }
        return code.toString();
    }

}

